package com.lanou.elh.sysmanage.authority_management.shiro;

import com.lanou.elh.sysmanage.authority_management.entity.Permission;
import com.lanou.elh.sysmanage.authority_management.entity.RolePerm;
import com.lanou.elh.sysmanage.authority_management.entity.User;
import com.lanou.elh.sysmanage.authority_management.mapper.UserMapper;
import com.lanou.elh.sysmanage.authority_management.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    /*获取授权信息*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权逻辑啦啦啦啦");
        String username = (String) principalCollection.getPrimaryPrincipal();
        String roles = userMapper.findRolesByUsername(username);
        System.out.println(roles);
       // Set<String>permissions = userMapper.findPermissionsByusername(username);
        Set<String> set = new HashSet<>();
        //需要将 role 封装到 Set 作为 info.setRoles() 的参数
        set.add(roles);
       SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
       info.setRoles(set);
    //   info.setStringPermissions(permissions);

        return info;

    }
    /*获取认证信息*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        //编写shiro认证逻辑，判断用户名和密码
        System.out.println("走的执行认证逻辑");
        UsernamePasswordToken token = (UsernamePasswordToken) arg0;
        User user = userService.selectUserByUserName(token.getUsername());
        if (user==null){
            //用户名不存在
            return null;
        }
        System.out.println("11111111111111111111111------"+user.getUsername());
        System.out.println("222222222222222222222222222------"+user.getPassword());
        System.out.println("333333333333333333333333333333------"+getName());
        return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());



    }
}
